<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
                        style="margin-bottom: 20px" />
                </div>
                <div class="head-container">
                    <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
                        :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
                </div>
            </el-col>
            <!--用户数据-->

            <!--用户搜索框-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="选择日期" prop="date">
                        <el-date-picker v-model="queryParams.localDate" value-format="yyyy-MM" default-value default-time
                            :clearable="false" :editable="false" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                </el-row>
                <el-row :gutter="10" class="mb8">
                    <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
                </el-row>
                <!--用户列表-->
                <el-table v-loading="loading" :data="archiveList" :row-style="{ height: '100px' }"
                    :cell-style="{ padding: '1px' }">
                    <!-- <el-table-column label="ID" prop="id" width="50" align="center" /> -->

                    <el-table-column label="日期" prop="archiveDate" width="100" align="center">
                    </el-table-column>
                    <el-table-column label="状态" prop="status" width="130" align="center">
                        <template slot-scope="scope">
                            <div>
                                <el-tag v-if="scope.row.status == 1"> 已归档 </el-tag>
                                <el-tag type="warning" v-else-if="scope.row.status == 0"> 未归档 </el-tag>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="创建时间" align="center" prop="createTime" />

                    <el-table-column label="创建人" align="center" prop="User" />

                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button @click="handleClick(scope.row)" type="primary" plain size="small"
                                v-if="scope.row.status">详情</el-button>
                            <el-button @click="handleDelete(scope.row, scope.$index)" type="warn" plain size="small"
                                v-if="scope.row.status">删除</el-button>

                            <el-button @click="handleCreate(scope.row, scope.$index)" size="small" v-else>创建</el-button>

                        </template>
                    </el-table-column>
                </el-table>

                <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
            </el-col>
        </el-row>

        <!--  创建归档-->

        <el-dialog title="归档" :visible.sync="dialogFormVisible" width="60%" :before-close="handleClose">
            <div class="text item">
                <el-descriptions title="统计" :column="2" direction="vertical" border>
                    <!-- 第一行 -->
                    <el-descriptions-item label="所属部门">{{ this.form.deptName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="归档月份">{{ this.form.archiveDate }}
                    </el-descriptions-item>
                </el-descriptions>
                <hr>
            </div>

            <div class="streamline">
                <el-descriptions title="明细" :column="3" direction="vertical" border>
                </el-descriptions>
                <template>
                    <el-table v-loading="loading" :data="userList">
                        <!-- <el-table-column type="selection" width="50" align="center" /> -->
                        <el-table-column label="序号" type="index" width="50" align="center" />
                        <el-table-column label="姓名" align="center" key="nickName" prop="nickName" v-if="columns[2].visible"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="用户名" align="center" key="userName" prop="userName" v-if="columns[1].visible"
                            :show-overflow-tooltip="true" />
                        <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" /> -->
                        <el-table-column label="职位" align="center" key="postName" prop="postName" width="140"
                            v-if="columns[0].visible" />
                        <el-table-column prop="monthTotal" label="应报天数" align="center">
                        </el-table-column>
                        <el-table-column prop="fillTotal" label="实报天数" align="center">
                        </el-table-column>
                        <el-table-column prop="leaveTotal" label="请假天数" align="center">
                        </el-table-column>
                        <el-table-column prop="paidLeaveTotal" label="倒休天数" align="center">
                        </el-table-column>

                        <el-table-column prop="missFillTotal" label="缺报天数" align="center">
                            <template slot-scope="scope">
                                <span>{{ scope.row.monthTotal - scope.row.fillTotal - scope.row.leaveTotal
                                    - scope.row.paidLeaveTotal
                                }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="useHour" label="上报率" align="center">
                            <template slot-scope="scope">
                                <span>{{ Number((scope.row.fillTotal + scope.row.leaveTotal + scope.row.paidLeaveTotal) /
                                    scope.row.monthTotal * 100).toFixed(2) }} % </span>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button @click="handlePerson(scope.row)" type="primary" size="small">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </template>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="submitCreate">开始归档</el-button>
            </span>
        </el-dialog>




        <el-dialog title="人员月统计详情" :visible.sync="projectDialog" width="75%">
            <div class="text item">
                <el-descriptions title="统计" :column="3" direction="vertical" border>
                    <!-- 第一行 -->
                    <el-descriptions-item label="上报总计">{{ detail.fillTotal }}天
                    </el-descriptions-item>
                    <el-descriptions-item label="上报-工作日天数">{{ detail.fillTotal - detail.overtimeTotal }}天
                    </el-descriptions-item>
                    <el-descriptions-item label="上报-加班天数">{{ detail.overtimeTotal }}天
                    </el-descriptions-item>

                    <!-- 第二行 -->
                    <el-descriptions-item label="请假调休总计">{{ detail.leaveTotal + detail.paidLeaveTotal }}天
                    </el-descriptions-item>

                    <el-descriptions-item label="请假">{{ detail.leaveTotal }}天
                    </el-descriptions-item>
                    <el-descriptions-item label="调休">{{ detail.paidLeaveTotal }}天
                    </el-descriptions-item>

                    <!-- 第二行 -->
                    <el-descriptions-item label="出勤小计">{{ detail.fillTotal + detail.leaveTotal + detail.paidLeaveTotal }}天
                    </el-descriptions-item>


                    <el-descriptions-item label="缺报">{{ detail.missFillTotal }}天
                    </el-descriptions-item>

                    <el-descriptions-item label="应报总数">{{ detail.monthTotal }}天
                    </el-descriptions-item>
                    <!-- <el-descriptions-item label="小计">{{ detail.mustFillNum  }}天（含加班）
          </el-descriptions-item> -->
                </el-descriptions>
                <div style="font-size: large;margin-top: 10px;">
                    上报率:{{ Number(detail.reportRate).toFixed(2) }} % （上报总数/应报总数）

                </div>
                <hr>
            </div>

            <div class="streamline">
                <el-descriptions title="明细" :column="3" direction="vertical" border>
                </el-descriptions>
                <template>
                    <el-table :data="projectList" border style="width: 100%">
                        <el-table-column type="index" label="序号" align="center" width="52px">
                        </el-table-column>
                        <el-table-column prop="date" label="日期" align="center" width="109px">
                        </el-table-column>
                        <!-- <el-table-column prop="nickName" label="人员" align="center">
              </el-table-column> -->
                        <!-- <el-table-column prop="postName" label="岗位" align="center">
              </el-table-column> -->
                        <el-table-column prop="status" label="状态" align="center" width="109px">
                            <template slot-scope="scope">
                                <div>
                                    <el-tag v-if="scope.row.status == 1"><i class="el-icon-check"></i> 已填报
                                    </el-tag>
                                    <el-tag type="danger" v-else-if="scope.row.status == 2"><i class="el-icon-close"></i> 缺报
                                    </el-tag>
                                    <el-tag type="info" v-else-if="scope.row.status == 3"><i class="el-icon-minus"></i> 无需填报
                                    </el-tag>
                                    <el-tag type="success" v-else-if="scope.row.status == 4"><i
                                            class="el-icon-magic-stick"></i> 节假日
                                    </el-tag>
                                    <el-tag type="warning" v-else-if="scope.row.status == 5"><i
                                            class="el-icon-close-notification"></i>
                                        请假
                                    </el-tag>
                                    <el-tag type="warning" v-else-if="scope.row.status == 6"><i class="el-icon-refresh"></i>
                                        调休
                                    </el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="totalHour" label="上报工时" align="center" width="80">
                        </el-table-column>
                        <el-table-column prop="useHour" label="详情" align="center" min-width="200">
                            <template slot-scope="scope" class="table-item">
                                <div>
                                    <el-table :data="scope.row.projectHours" style="width: 100%" :border="false"
                                        :show-header="false">
                                        <el-table-column prop="projectName" label="项目" align="center">
                                        </el-table-column>
                                        <el-table-column prop="useHour" label="工时" align="center">
                                            <template slot-scope="scope">
                                                <span>{{ scope.row.useHour }}小时</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="daily" label="日志" align="center">
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="fillTime" label="上报时间" width="80" align="center">
                        </el-table-column>
                        <!-- <el-table-column prop="address" label="地址"> </el-table-column> -->
                    </el-table>
                </template>
            </div>


            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="closeForm">取 消</el-button>
        <el-button type="primary" @click="closeForm">确 定</el-button> -->
            </span>


        </el-dialog>


        <!--  归档详情-->
        <el-dialog title="详情" :visible.sync="detailFormVisible" width="75%" :before-close="handleClose">
            <div class="text item">
                <el-descriptions title="统计" :column="2" direction="vertical" border>
                    <!-- 第一行 -->
                    <el-descriptions-item label="所属部门">{{ this.form.deptName }}
                    </el-descriptions-item>
                    <el-descriptions-item label="归档月份">{{ this.archiveDetail.archiveDate }}
                    </el-descriptions-item>
                    <el-descriptions-item label="归档时间">{{ this.archiveDetail.createTime }}
                    </el-descriptions-item>
                </el-descriptions>
                <hr>
            </div>
            <div class="streamline">
                <el-descriptions title="明细" :column="3" direction="vertical" border>
                </el-descriptions>
                <template>
                    <el-table v-loading="loading" :data="userList">
                        <!-- <el-table-column type="selection" width="50" align="center" /> -->
                        <el-table-column label="序号" type="index" width="50" align="center" />
                        <el-table-column label="姓名" align="center" key="nickName" prop="nickName" v-if="columns[2].visible"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="用户名" align="center" key="userName" prop="userName" v-if="columns[1].visible"
                            :show-overflow-tooltip="true" />
                        <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" /> -->
                        <el-table-column label="职位" align="center" key="postName" prop="postName" width="140"
                            v-if="columns[0].visible" />
                        <el-table-column prop="monthTotal" label="应报天数" align="center">
                        </el-table-column>
                        <el-table-column prop="fillTotal" label="实报天数" align="center">
                        </el-table-column>

                        <el-table-column prop="leaveTotal" label="请假天数" align="center">
                        </el-table-column>
                        <el-table-column prop="paidLeaveTotal" label="倒休天数" align="center">
                        </el-table-column>

                        <el-table-column prop="missFillTotal" label="缺报天数" align="center">
                            <template slot-scope="scope">
                                <span>{{ scope.row.monthTotal - scope.row.fillTotal - scope.row.leaveTotal
                                    - scope.row.paidLeaveTotal
                                }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="useHour" label="上报率" align="center">
                            <template slot-scope="scope">
                                <span>{{ Number((scope.row.fillTotal + scope.row.leaveTotal + scope.row.paidLeaveTotal) /
                                    scope.row.monthTotal * 100).toFixed(2) }} % </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button @click="handlePerson(scope.row)" type="primary" size="small">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </template>
            </div>







        </el-dialog>

    </div>
</template>
  
<script>

import { getArchiveList, createArchive, getArchive,deleteArchive } from "@/api/mhmanage/archive";

import { getDeptMontStat, } from "@/api/workingHour/deptHour";

import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    exportUser,
    resetUserPwd,
    changeUserStatus,
    importTemplate
} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import { getRate } from "@/api/dataStat/rate";


import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getMyHourDetailt, getUserHourStat } from "@/api/system/project";


export default {
    name: "mharchive",
    components: { Treeselect },
    data() {
        return {
            tableHeight: "",
            // 遮罩层
            loading: false,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数


            // 弹出层标题
            title: "",
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 部门名称
            deptName: undefined,


            // 日期范围
            dateRange: [],
            // 状态数据字典

            defaultProps: {
                children: "children",
                label: "label"
            },

            // 查询参数
            queryParams: {
                pageSize: 10,
                deptId: undefined,
                startDate: "",
                endDate: "",
            },
            dialogFormVisible: false,
            detailFormVisible: false,

            // 列信息
            columns: [
                { key: 0, label: `用户编号`, visible: true },
                { key: 1, label: `用户名称`, visible: true },
                { key: 2, label: `用户姓名`, visible: true },
                { key: 3, label: `部门`, visible: true },
                { key: 4, label: `手机号码`, visible: true },
                { key: 5, label: `状态`, visible: true },
                { key: 6, label: `创建时间`, visible: true }
            ],

            form: {
                archiveDate: "",
                deptId: 0,
                deptName: null,
            },

            // 表单校验
            rules: {
            },

            //创建归档
            deptHour: [],
            userList: [],
            total: 0,

            //创建归档人员详情
            projectDialog: false,
            detail: {
                month: "",
                monthTotal: 0,
                fillTotal: 0,
                missFillTotal: 0,
                overtimeTotal: 0,
                leaveTotal: 0,
                paidLeaveTotal: 0,
                reportRate: 0,
            },
            projectList: [],



            //返回数据
            archiveList: [],
            indexs: 0,
            archiveDetail: {},

        };
    },
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
    },
    mounted() {
        //挂载window.onresize事件(动态设置table高度)
        let _this = this;
        window.onresize = () => {
            if (_this.resizeFlag) {
                clearTimeout(_this.resizeFlag);
            }
            _this.resizeFlag = setTimeout(() => {
                _this.getTableHeight();
                _this.resizeFlag = null;
            }, 100);
        };
    },
    created() {

        // this.getList();
        this.getTreeselect();
        this.getTableHeight();
    },
    methods: {
        /** 查询归档列表 */
        getList() {
            this.loading = true;
            getArchiveList(this.queryParams).then(
                response => {
                    if (response.code == 200) {
                        this.archiveList = response.data;
                        this.loading = false;
                    }
                }
            );
        },

        // 工具类
        unique(newarr) {
            let arr = newarr;
            let result = {};
            let finalResult = [];
            for (let i = 0; i < arr.length; i++) {
                //利用对象的键名无法重复的特点，cppostName是唯一区别的属性值
                result[arr[i].postName]
                    ? ""
                    : (result[arr[i].postName] = true && finalResult.push(arr[i]));
            }
            return finalResult;
        },

        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id;
            this.form.deptName = data.label;
            this.getList();
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                startDate: undefined,
                endDate: undefined,
                status: "0",


            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleResetPwd":
                    this.handleResetPwd(row);
                    break;
                case "handleAuthRole":
                    this.handleAuthRole(row);
                    break;
                default:
                    break;
            }
        },


        handleClose() {
            // this.detail= ""
            this.dialogFormVisible = false;
            this.detailFormVisible = false;

        },



        //计算table高度(动态设置table高度)
        getTableHeight() {
            let tableH = 840; //距离页面下方的高度
            let tableHeightDetil = window.innerHeight - tableH;
            if (tableHeightDetil <= 240) {
                this.tableHeight = 240;
            } else {
                this.tableHeight = window.innerHeight - tableH;
            }
        },


        // 归档详情
        handleClick(row) {
            this.detailFormVisible = true;
            let queryParams = { deptId: row.deptId, month: row.archiveDate }

            getArchive(row.id).then(res => {
                // console.log("getMyHourDetailt", res);
                if (res.code == 200) {
                    this.archiveDetail = res.data;

                }
                if (res.code == 500) return;
            });
            getRate(queryParams).then(
                response => {
                    if (response.code == 200) {
                        this.userList = response.rows;
                        this.total = response.total;
                    }
                }
            );
        },

        // 创建归档
        handleCreate(row, index) {
            console.log(row);
            this.indexs = index;
            this.dialogFormVisible = true;
            this.form.archiveDate = row.archiveDate;
            this.form.deptId = row.deptId;

            let queryParams = { deptId: row.deptId, month: row.archiveDate }

            getRate(queryParams).then(
                response => {
                    if (response.code == 200) {
                        this.userList = response.rows;
                        this.total = response.total;
                    }
                }
            );

        },

        //创建时查看人员详情
        handlePerson(row) {
            this.projectDialog = true
            this.detail.month = row.month
            this.detail.monthTotal = row.monthTotal
            this.detail.fillTotal = row.fillTotal
            this.detail.leaveTotal = row.leaveTotal
            this.detail.paidLeaveTotal = row.paidLeaveTotal

            //计算内容
            this.detail.missFillTotal = row.monthTotal - row.fillTotal - row.leaveTotal - row.paidLeaveTotal
            this.detail.reportRate = row.fillTotal / row.monthTotal * 100

            this.getDataDetail(row.userId);

        },
        getDataDetail(userId) {
            let date = this.detail.month + "-01"
            getUserHourStat(date, userId).then(res => {
                // console.log(res);
                if (res.code == 200) {
                    this.stat = res.data;
                    //console.log("this.stat", this.stat);
                    this.projectList = res.data;
                    // this.peopleday = res.data.projectHours.length;
                    // console.log(this.projectList);
                    this.projectList.forEach(el => {
                        el.totalHour = 0;
                        if (el.projectHours != null) {
                            el.projectHours.forEach(fl => {
                                el.totalHour += fl.useHour;
                            });
                        }
                    });
                    // console.log("project", this.projectList);
                }
            });
        },


        //提交归档
        submitCreate() {
            console.log("要提交的参数", this.form);
            createArchive(this.form)
                .then(res => {
                    // console.log(res);
                    if (res.code == 200) {
                        //this.init();
                        this.$message.success("归档提交成功");
                        this.dialogFormVisible = false;
                        this.archiveList[this.indexs].status = 1;
                        this.archiveList[this.indexs].createTime = "已填报";
                        this.tableData[this.indexs].id = res.data;
                        //this.tableData[this.indexs].reviewStatus = -1;
                    } else {
                        this.$message.error("提交失败，失败原因为：", res.msg);
                        //this.dialogFormVisible = false;
                        //this.init();
                    }
                })
                .catch(err => {
                    console.log(err);
                    //this.dialogFormVisible = false;
                    //this.init();
                });

        },
        //删除归档
        handleDelete(row,index){
            this.indexs = index;
            deleteArchive(row.id).then(res => {
                // console.log("getMyHourDetailt", res);
                if (res.code == 200) {
                    this.$message.success("删除成功");
                    this.archiveList[this.indexs].status= 0;
                    this.archiveList[this.indexs].createTime = "";
                    this.archiveList[this.indexs].id = "";
                }
                if (res.code == 500) {
                    this.$message.error("提交失败，失败原因为：", res.msg);
                } return;
            });
        },
    }
};
</script>
<style scoped lang="scss">
.collapse-content {
    span {
        margin-right: 8px;
    }
}


.el-tabs--card {
    height: calc(100vh - 110px);
    /* overflow-y: auto; */
}

.el-tab-pane {
    height: calc(100vh - 110px);
    overflow-y: auto;
}

.detail {
    width: 65%;
    margin: 0 auto;
}

.el-row {
    margin-bottom: 20px;

    &:last-child {
        margin-bottom: 0;
    }
}

.el-col {
    border-radius: 4px;
}

.bg-purple {
    background: #d3dce6;
}

.bg-purple-light {
    background: #e5e9f2;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

.row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
}

.btns {
    padding: 0 12px;
}

.el-select.el-select--medium {
    margin: 0 8px;
}
</style>
  